package com.tanhua.controller;

import com.itheima.commons.utils.Constants;
import com.tanhua.dubbo.api.UserApi;
import com.tanhua.exception.BusinessException;
import com.tanhua.interceptor.UserHolder;
import com.tanhua.model.domain.User;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.vo.CountsLikeVo;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.model.vo.PageResult;
import com.tanhua.model.vo.UserInfoVo;
import com.tanhua.server.TanhuaService;
import com.tanhua.server.UserInfoService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/users")
public class UsersController {
    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private UserApi userApi;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    private TanhuaService tanhuaService;

    @GetMapping
    public ResponseEntity<UserInfoVo> getUserInfo(Long userID, @RequestHeader("Authorization") String token) {
//        String id1 = JwtUtils.getClaims(token).get("id").toString();
//        long id = Long.parseLong(id1);

        if (userID == null) {
            userID = UserHolder.getUserId();
        }
        UserInfoVo userInfo = userInfoService.getById(userID);
        if (userInfo == null) {
            throw new BusinessException(ErrorResult.builder().errMessage("请完善信息后重试").build());
        }

//        UserInfoVo userInfoVo = new UserInfoVo();
//        BeanUtils.copyProperties(userInfo, userInfoVo);
//        userInfoVo.setId(Math.toIntExact(id));
//        if (userInfo.getAge() != null) {
//            userInfoVo.setAge(null);
//        }
        return ResponseEntity.ok(userInfo);
    }

    @PutMapping
    public ResponseEntity<Void> updateUsers(@RequestHeader("Authorization") String token,
                                            @RequestBody UserInfo userInfo) {
//        Claims claims = JwtUtils.getClaims(token);
//        String id = claims.get("id").toString();
//        long ID = Long.parseLong(id);
        Long id = UserHolder.getUserId();
        userInfo.setId(id);
        userInfoService.updateUsers(userInfo);
        return ResponseEntity.ok(null);
    }

    @PostMapping("/header")
    public ResponseEntity<Void> updateHeaders(MultipartFile headPhoto) throws IOException {
        userInfoService.updateHead(headPhoto, UserHolder.getUserId());
        return ResponseEntity.ok(null);
    }

    //修改手机号，发送验证码
    @PostMapping("/phone/sendVerificationCode")
    public ResponseEntity<Void> sendVerificationCode(HttpServletResponse response) {
        User user = userApi.findByUserId(UserHolder.getUserId());
        if (user == null) {
            throw new BusinessException(ErrorResult.builder().errMessage("手机号错误").errCode("402").build());
        }
        String key = Constants.PHONE_CODE + UserHolder.getUserId();
        String code = "123456";

        redisTemplate.opsForValue().set(key, code, 5, TimeUnit.MINUTES);
        return ResponseEntity.ok(null);
    }

    //校验验证码
    @PostMapping("/phone/checkVerificationCode")
    public ResponseEntity<Map<String, Boolean>> checkVerificationCode(@RequestBody Map map) {
        String verificationCode = map.get("verificationCode").toString();
        String key = Constants.PHONE_CODE + UserHolder.getUserId();
        String code = redisTemplate.opsForValue().get(key);
        if (StringUtils.isEmpty(code) || !code.equals(verificationCode)) {
            throw new BusinessException(ErrorResult.builder().errMessage("验证码不正确").build());
        }
        HashMap<String, Boolean> hashMap = new HashMap<>();
        hashMap.put("verification", true);
        return ResponseEntity.ok(hashMap);
    }

    //修改手机号
    @PostMapping("/phone")
    public ResponseEntity<Void> updatePhone(@RequestBody Map map) {
        String phone = map.get("phone").toString();
        Boolean aBoolean = userApi.exist(phone);
        if (aBoolean) {
            throw new BusinessException(ErrorResult.mobileError());
        }
        userApi.updatePhone(UserHolder.getUserId(), phone);
        return ResponseEntity.ok(null);
    }

    //互相喜欢、喜欢、粉丝、谁看过我 - 翻页列表
    @GetMapping("/friends/{type}")
    public ResponseEntity<PageResult> ListByType(@RequestParam(defaultValue = "1") Integer page,
                                                 @RequestParam(defaultValue = "10") Integer pagesize,
                                                 @PathVariable("type") Integer type,
                                                 String nickname) {
        PageResult pageResult = userInfoService.ListByType(page, pagesize, type, nickname);
        return ResponseEntity.ok(pageResult);
    }

    //互相喜欢，喜欢，粉丝 - 统计
    @GetMapping("/counts")
    public ResponseEntity<CountsLikeVo> getCounts() {
        CountsLikeVo countsLikeVo = userInfoService.getCounts();
        return ResponseEntity.ok(countsLikeVo);
    }

    //喜欢 - 取消
    @DeleteMapping("/like/{uid}")
    public ResponseEntity<Void> disLike(@PathVariable Long uid) {
        tanhuaService.dislikeUser(uid);
        return ResponseEntity.ok(null);
    }
}
